package com.cpan.android.sms.data;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class PhraseDBHelper {
	private final static String TAG = "PhraseDBHelper";
	public final static boolean debug = true;

	private final static String DB_NAME = "sms_show.db";
	private final static int DB_VERSION = 2;
	private final static String TABLE_PHRASE = "T_PHRASE";

	public final static String KEY_ID = "_id";
	public final static String KEY_PHRASE = "PHRASE";
	public final static String KEY_DATE = "DATE";

	public static String[] PHARASE_PROJECTION = new String[] { KEY_ID,
			KEY_PHRASE, KEY_DATE };
	public final static String ASC = " ASC";
	public final static String DESC = " DESC";
	public final static String SQL_CREATE_TABLE = "CREATE TABLE "
			+ TABLE_PHRASE + " (" + KEY_ID + " INTEGER PRIMARY KEY ,"
			+ KEY_PHRASE + " TEXT," + KEY_DATE + " TEXT )";
	public final static String SQL_DROP_TABEL = "DROP TABLE IF EXISTS "
			+ TABLE_PHRASE;

	private Context mContext;
	private SQLiteDatabase mSQLiteDatabase;
	private PhraseDatabaseHelper mPhraseDatabaseHelper;

	public PhraseDBHelper(Context context) {
		mContext = context;
	}

	public void open() {
		mPhraseDatabaseHelper = new PhraseDatabaseHelper(mContext);
		mSQLiteDatabase = mPhraseDatabaseHelper.getWritableDatabase();
	}

	public void close() {
		mSQLiteDatabase.close();
		mPhraseDatabaseHelper.close();

	}

	public long insert(String phrase, String date) {
		ContentValues cv = new ContentValues();
		cv.put(KEY_PHRASE, phrase);
		cv.put(KEY_DATE, date);
		return mSQLiteDatabase.insert(TABLE_PHRASE, null, cv);
	}

	public int delete(long keyID) {
		String whereClause = " " + KEY_ID + "=" + keyID;
		return mSQLiteDatabase.delete(TABLE_PHRASE, whereClause, null);
	}

	public Cursor fetchAll() {
		return mSQLiteDatabase.query(TABLE_PHRASE, PHARASE_PROJECTION, null,
				null, null, null, null);
	}

	public Cursor fetchByID(long id) {
		String selection = " " + KEY_ID + "=" + id;
		Cursor cursor = mSQLiteDatabase.query(TABLE_PHRASE, PHARASE_PROJECTION,
				selection, null, null, null, KEY_DATE);
		if (cursor != null)
			cursor.moveToFirst();
		return cursor;
	}

	private static class PhraseDatabaseHelper extends SQLiteOpenHelper {

		public PhraseDatabaseHelper(Context context) {
			super(context, DB_NAME, null, DB_VERSION);
			if (debug)
				Log.e(TAG, "PhraseDatabaseHelper");
		}

		public void onCreate(SQLiteDatabase db) {
			if (debug)
				Log.e(TAG, "onCreate");
			db.execSQL(SQL_CREATE_TABLE);
		}

		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			if (debug)
				Log.e(TAG, "onUpgrade");
			db.execSQL(SQL_DROP_TABEL);
			onCreate(db);
		}

	}
}
